#!/usr/bin/perl
###############################################################################

use strict;
use warnings;

my $tileIn = 'MAINTILE.BIN';
my $tileOut = 'MAINTIL2.BIN';

open(TILEIN, "<$tileIn") or die "Bad file open\n";
binmode TILEIN;

open(TILEOUT, ">$tileOut") or die "Bad file open\n";
binmode TILEOUT;

my $tileInLength = (-s $tileIn);

my $tileInBuffer = '';
if ( read(TILEIN,$tileInBuffer,$tileInLength) != $tileInLength ) {
    die "Bad file read\n";
}

close TILEIN;

for ( my $i = 0; $i < $tileInLength; $i++ ) {
    my $value = ord(substr($tileInBuffer,$i,1));
    for ( my $j = 0; $j < 8; $j += 2 ) {
	my $chr = chr( ( ( ( $value & ( 1 << ( 7 - $j ) ) ) ? 2 : 1 ) << 4 ) |
		       ( ( ( $value & ( 1 << ( 6 - $j ) ) ) ? 2 : 1 )      ) );
	print TILEOUT $chr;
    }
}

close TILEOUT;
